package response

import (
	"gin-skeleton/core"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 定义内置响应
var (
	InternalError  = core.Error{Code: -1, Msg: "Internal error: %s"}
	ParameterError = core.Error{Code: -3, Msg: "Parameter error: %s"}
)

type ApiResponse struct {
	Code      int         `json:"code"`
	Message   string      `json:"msg"`
	Data      interface{} `json:"data"`
	RequestId string      `json:"log_id"`
	c         *gin.Context
}

func Api(c *gin.Context) *ApiResponse {
	return &ApiResponse{
		c:       c,
		Message: "Success",
		Code:    0,
	}
}

func (r *ApiResponse) SetMessage(msg string) *ApiResponse {
	r.Message = msg
	return r
}

// Success 成功
func (r *ApiResponse) Success(data ...interface{}) {
	r.Data = data
	r.returnJson(http.StatusOK)
}

// Fail 失败
func (r *ApiResponse) Fail(code int, data ...interface{}) {
	r.Code = code
	r.Data = data
	r.returnJson(http.StatusOK)
}

// 错误
func (r *ApiResponse) Error(err *core.Error) {
	r.Code = err.Code
	r.Message = err.Msg
	r.returnJson(http.StatusInternalServerError)
	go err.Log()
}

func (r *ApiResponse) returnJson(code int) {
	if requestId, ok := r.c.Get(core.RequestID); ok {
		r.RequestId = requestId.(string)
	}
	r.c.Header(core.RequestID, r.RequestId)
	r.c.JSON(code, r)
}
